package cn.edu.baiyunu.myapplication.ui.navigation

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PagerState
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Add
import androidx.compose.material.icons.rounded.Home
import androidx.compose.material.icons.rounded.List
import androidx.compose.material.icons.rounded.Person
import androidx.compose.material.icons.rounded.ShowChart
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.FloatingActionButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.zIndex
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import cn.edu.baiyunu.myapplication.ui.screens.add.AddTransactionScreen
import cn.edu.baiyunu.myapplication.ui.screens.budget.BudgetScreen
import cn.edu.baiyunu.myapplication.ui.screens.home.HomeScreen
import cn.edu.baiyunu.myapplication.ui.screens.profile.ProfileScreen
import cn.edu.baiyunu.myapplication.ui.screens.profile.SavingsGoalScreen
import cn.edu.baiyunu.myapplication.ui.screens.settings.SettingsScreen
import cn.edu.baiyunu.myapplication.ui.screens.statistics.StatisticsScreen
import cn.edu.baiyunu.myapplication.ui.screens.transactions.TransactionDetailScreen
import cn.edu.baiyunu.myapplication.ui.screens.transactions.TransactionsScreen
import cn.edu.baiyunu.myapplication.ui.screens.add.BasicAddTransactionScreen
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.animation.core.LinearOutSlowInEasing
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.togetherWith

/**
 * 应用导航目的地
 */
sealed class Screen(val route: String, val icon: ImageVector? = null, val label: String = "") {
    // 主要导航项目
    object Home : Screen("home", Icons.Rounded.Home, "首页")
    object Transactions : Screen("transactions", Icons.Rounded.List, "交易")
    object AddTransaction : Screen("add_transaction", Icons.Rounded.Add, "记账")
    object Statistics : Screen("statistics", Icons.Rounded.ShowChart, "统计")
    object Profile : Screen("profile", Icons.Rounded.Person, "我的")
    
    // 子页面（不在底部导航中显示）
    object TransactionDetail : Screen("transaction_detail/{transactionId}") {
        fun createRoute(transactionId: String) = "transaction_detail/$transactionId"
    }
    object Budget : Screen("budget")
    object Settings : Screen("settings")
    object SavingsGoal : Screen("savings_goal")
    
    companion object {
        val mainNavItems = listOf(Home, Transactions, Statistics, Profile)
        
        // 定义应用的主题色渐变 - 较深的主题色
        val themeGradient = Brush.linearGradient(
            colors = listOf(
                Color(0xFF6A11CB),
                Color(0xFF2575FC)
            )
        )
        
        // 定义更亮的渐变色 - 浮动按钮颜色
        val brightThemeGradient = Brush.linearGradient(
            colors = listOf(
                Color(0xFF8C5CF5), // 更亮的紫色
                Color(0xFF59A5FF)  // 更亮的蓝色
            )
        )
        
        // 定义更浅的底部导航栏渐变色
        val lightNavBarGradient = Brush.linearGradient(
            colors = listOf(
                Color(0xFF9D78F3), // 非常浅的紫色
                Color(0xFF7CB8FF)  // 非常浅的蓝色
            )
        )
        
        // 定义与内容底部协调的渐变色（由深到浅的渐变）
        val contentBottomGradient = Brush.linearGradient(
            colors = listOf(
                Color(0xFF5A20BC), // 深色调的紫色
                Color(0xFFBA29D3)  // 中等亮度的蓝色
            )
        )
    }
}

// 添加可变全局状态记录选中的标签索引
// 注意：在实际应用中，这不是最佳实践，理想情况下应使用ViewModel或状态提升
// 但为了快速修复当前编译错误，我们添加这个变量
var selectedTabIndex by mutableIntStateOf(0)

/**
 * 应用主导航组件
 */
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun BudgetNavigation() {
    val navController = rememberNavController()
    
    // 定义导航起始页
    val startDestination = Screen.Home.route
    
    // 使用可保存的状态来记住当前选择的页面索引 - 与全局变量同步
    var localSelectedTabIndex by rememberSaveable { mutableIntStateOf(selectedTabIndex) }
    
    // 创建静态的安全导航项目列表
    val navItems = listOf(
        Screen.Home,
        Screen.Transactions,
        Screen.Statistics,
        Screen.Profile
    )
    
    // 为页面创建pager状态
    val pagerState = rememberPagerState(initialPage = localSelectedTabIndex) { navItems.size }
    
    // 创建协程作用域
    val coroutineScope = rememberCoroutineScope()
    
    // 使用LaunchedEffect和snapshotFlow监听页面变化
    LaunchedEffect(pagerState) {
        snapshotFlow { pagerState.currentPage }
            .distinctUntilChanged()
            .collect { page ->
                if (localSelectedTabIndex != page) {
                    localSelectedTabIndex = page
                    selectedTabIndex = page
                }
            }
    }
    
    // 监听页面索引变化，确保pager状态同步
    LaunchedEffect(localSelectedTabIndex) {
        // 增加日志，帮助调试页面切换问题
        println("BudgetNavigation - 导航索引变化: selectedTabIndex = $localSelectedTabIndex, 当前页面 = ${pagerState.currentPage}")
        
        // 如果选择的标签索引和当前页面不同，立即滚动到选定页面
        if (pagerState.currentPage != localSelectedTabIndex) {
            println("BudgetNavigation - 尝试切换页面从 ${pagerState.currentPage} 到 $localSelectedTabIndex")
            try {
                // 使用animateScrollToPage有时会被动画打断，导致不完全切换
                // 对于从"我的"到"首页"的远距离跳转，直接使用scrollToPage更可靠
                if ((localSelectedTabIndex == 0 && pagerState.currentPage == 3) || 
                    Math.abs(localSelectedTabIndex - pagerState.currentPage) > 1) {
                    // 直接跳转，无动画
                    println("BudgetNavigation - 使用无动画方式切换页面")
                    pagerState.scrollToPage(localSelectedTabIndex)
                } else {
                    // 短距离切换使用动画
                    println("BudgetNavigation - 使用动画方式切换页面")
                    pagerState.animateScrollToPage(localSelectedTabIndex)
                }
                println("BudgetNavigation - 页面滚动请求完成: 目标页面 = $localSelectedTabIndex")
            } catch (e: Exception) {
                println("BudgetNavigation - 页面滚动错误: ${e.message}")
                // 如果动画失败，尝试直接设置
                pagerState.scrollToPage(localSelectedTabIndex)
            }
        } else {
            println("BudgetNavigation - 页面已经在目标位置，无需切换")
        }
    }

    // 用于触发FAB导航的状态
    var shouldNavigateToAddTransaction by remember { mutableStateOf(false) }
    
    // 获取当前导航目的地，用于判断是否显示底部导航栏
    val navBackStackEntry by navController.currentBackStackEntryAsState()
    val currentRoute = navBackStackEntry?.destination?.route
    
    // 检查当前路由是否是主导航路由之一
    val showBottomBar = currentRoute in navItems.map { it.route }

    // 处理添加交易页面的导航
    if (shouldNavigateToAddTransaction) {
        LaunchedEffect(shouldNavigateToAddTransaction) {
            navController.navigate(Screen.AddTransaction.route)
            // 重置状态防止多次触发
            shouldNavigateToAddTransaction = false
        }
    }

    // 创建基础的脚手架UI
    Scaffold(
        modifier = Modifier.fillMaxSize(),
        containerColor = Color.Transparent,
        contentColor = Color.White,
        bottomBar = {
            // 使用AnimatedVisibility包装底部导航栏实现平滑切换
            AnimatedVisibility(
                visible = showBottomBar,
                enter = slideInVertically(initialOffsetY = { it/2 }) + fadeIn(animationSpec = tween(300)),
                exit = slideOutVertically(targetOffsetY = { it/2 }) + fadeOut(animationSpec = tween(300))
            ) {
                SimpleBottomNavigation(
                    selectedTabIndex = localSelectedTabIndex,
                    items = navItems,
                    onTabSelected = { index ->
                        // 安全地检查索引范围
                        if (index in navItems.indices && index != localSelectedTabIndex) {
                            // 更新选中的索引
                            localSelectedTabIndex = index
                            selectedTabIndex = index
                        }
                    }
                )
            }
        },
        // 主页添加记账按钮，使用AnimatedVisibility实现平滑切换
        floatingActionButton = {
            AnimatedVisibility(
                visible = localSelectedTabIndex == 0 && showBottomBar,
                enter = scaleIn(animationSpec = tween(300)) + fadeIn(animationSpec = tween(300)),
                exit = scaleOut(animationSpec = tween(300)) + fadeOut(animationSpec = tween(300))
            ) {
                AddTransactionFAB {
                    // 使用状态变量触发导航，而不是直接导航
                    shouldNavigateToAddTransaction = true
                }
            }
        },
        contentWindowInsets = WindowInsets(0, 0, 0, 0)
    ) { paddingValues ->
        // 使用NavHost处理所有导航
        NavHost(
            navController = navController,
            startDestination = startDestination,
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {
            // 主页和所有水平滑动页面共享同一个组件
            composable(Screen.Home.route) {
                MainPagerScreen(
                    pagerState = pagerState,
                    navItems = navItems,
                    navController = navController
                )
            }
            
            // 添加其他页面路由
            composable(
                route = "${Screen.AddTransaction.route}?edit={edit}",
                arguments = listOf(
                    navArgument("edit") {
                        type = NavType.StringType
                        defaultValue = ""
                        nullable = true
                    }
                )
            ) { backStackEntry ->
                val transactionId = backStackEntry.arguments?.getString("edit") ?: ""
                var shouldNavigateHome by remember { mutableStateOf(false) }
                
                // 使用LaunchedEffect处理导航
                if (shouldNavigateHome) {
                    LaunchedEffect(true) {
                        navController.navigate(Screen.Home.route) {
                            popUpTo(Screen.Home.route) { inclusive = true }
                        }
                    }
                }
                
                AddTransactionScreen(
                    transactionId = transactionId,
                    onTransactionAdded = {
                        // 使用状态触发导航
                        shouldNavigateHome = true
                    },
                    onCancel = { 
                        navController.navigateUp() 
                    }
                )
            }
            
            composable(
                route = Screen.TransactionDetail.route,
                arguments = listOf(
                    navArgument("transactionId") { type = NavType.StringType }
                )
            ) { backStackEntry ->
                val transactionId = backStackEntry.arguments?.getString("transactionId") ?: ""
                TransactionDetailScreen(
                    transactionId = transactionId,
                    onBackClick = { navController.navigateUp() },
                    navigateToEditTransaction = { transactionId ->
                        // 先回到交易列表
                        navController.navigateUp()
                        // 然后导航到编辑页面
                        navController.navigate(Screen.AddTransaction.route + "?edit=$transactionId")
                    }
                )
            }
            
            composable(Screen.Budget.route) {
                BudgetScreen(
                    onBackClick = { navController.navigateUp() }
                )
            }
            
            composable(Screen.Settings.route) {
                SettingsScreen(
                    onBackClick = { navController.navigateUp() }
                )
            }
            
            // 储蓄目标管理页面
            composable(Screen.SavingsGoal.route) {
                SavingsGoalScreen(
                    onBackClick = { navController.navigateUp() }
                )
            }
        }
    }
}

/**
 * 简化版底部导航栏
 */
@Composable
private fun SimpleBottomNavigation(
    selectedTabIndex: Int,
    items: List<Screen>,
    onTabSelected: (Int) -> Unit
) {
    if (items.isEmpty()) return

    Box(
        modifier = Modifier
            .fillMaxWidth()
            .navigationBarsPadding()
            .height(65.dp)
            .background(Screen.lightNavBarGradient)
    ) {
        // 顶部分隔线
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(1.dp)
                .align(Alignment.TopCenter)
                .background(Color.White.copy(alpha = 0.2f))
        )
        
        // 导航项目
        Row(
            modifier = Modifier
                .fillMaxSize()
                .padding(vertical = 6.dp),
            horizontalArrangement = Arrangement.SpaceAround,
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 安全迭代导航项目
            items.forEachIndexed { index, screen ->
                val isSelected = index == selectedTabIndex
                NavItem(
                    icon = screen.icon ?: Icons.Rounded.Home,
                    label = screen.label.ifEmpty { "未命名" },
                    isSelected = isSelected,
                    onClick = { onTabSelected(index) }
                )
            }
        }
    }
}

/**
 * 添加交易按钮
 */
@Composable
private fun AddTransactionFAB(onClick: () -> Unit) {
    Box(
        modifier = Modifier
            .size(60.dp)
            .clip(CircleShape)
            .background(Color.White.copy(alpha = 0.25f))
            .clickable(onClick = onClick),
        contentAlignment = Alignment.Center
    ) {
        Icon(
            imageVector = Icons.Rounded.Add,
            contentDescription = "添加交易",
            tint = Color.White,
            modifier = Modifier.size(28.dp)
        )
    }
}

/**
 * 主要内容页面，包含水平滑动页面
 */
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun MainPagerScreen(
    pagerState: PagerState,
    navItems: List<Screen>,
    navController: NavHostController
) {
    // 获取协程作用域
    val coroutineScope = rememberCoroutineScope()
    
    // 使用安全的HorizontalPager实现滑动页面
    HorizontalPager(
        state = pagerState,
        modifier = Modifier.fillMaxSize()
    ) { page ->
        // 安全处理页码范围
        if (page !in navItems.indices) {
            // 显示回退页面
            Box(modifier = Modifier.fillMaxSize()) {
                Text("页面不存在", modifier = Modifier.align(Alignment.Center))
            }
            return@HorizontalPager
        }
        
        // 根据页码显示不同内容
        when (page) {
            0 -> HomeScreen(
                navigateToTransaction = { transactionId ->
                    val route = Screen.TransactionDetail.createRoute(transactionId)
                    navController.navigate(route)
                },
                navigateToAddTransaction = {
                    navController.navigate(Screen.AddTransaction.route)
                },
                navigateToAllTransactions = {
                    // 直接导航到交易页面，而不是仅设置索引
                    println("BudgetNavigation::MainPagerScreen - 点击了查看全部，直接导航到交易页面")
                    
                    // 更新选中的标签索引为1 (交易页)
                    selectedTabIndex = 1
                    
                    // 使用协程启动页面切换动画
                    coroutineScope.launch {
                        try {
                            // 滑动到交易页面
                            pagerState.animateScrollToPage(1)
                            println("页面切换成功: 当前页面 = ${pagerState.currentPage}")
                        } catch (e: Exception) {
                            println("页面切换失败: ${e.message}")
                            // 如果动画失败，使用无动画方式滑动
                            pagerState.scrollToPage(1)
                        }
                    }
                },
                navigateToStatistics = {
                    // 不需要导航，直接滑动到统计页
                },
                navigateToProfile = {},
                navigateToBudget = {
                    navController.navigate(Screen.Budget.route)
                },
                navigateToSettings = {
                    navController.navigate(Screen.Settings.route)
                }
            )
            1 -> TransactionsScreen(
                navigateToTransaction = { transactionId ->
                    val route = Screen.TransactionDetail.createRoute(transactionId)
                    navController.navigate(route)
                },
                navigateToAddTransaction = {
                    navController.navigate(Screen.AddTransaction.route)
                }
            )
            2 -> StatisticsScreen()
            3 -> ProfileScreen(
                navigateToSettings = {
                    navController.navigate(Screen.Settings.route)
                },
                navigateToBudgetManager = {
                    navController.navigate(Screen.Budget.route)
                },
                navigateToSavingsGoal = {
                    navController.navigate(Screen.SavingsGoal.route)
                },
                navigateToDataBackup = {
                    navController.navigate(Screen.Settings.route)
                },
                navigateToAbout = {
                    navController.navigate(Screen.Settings.route)
                },
                navigateToFAQ = {
                    navController.navigate(Screen.Settings.route)
                }
            )
            else -> Box(modifier = Modifier.fillMaxSize()) // 永远不会到达这里
        }
    }
}

/**
 * 单个导航项
 */
@Composable
private fun NavItem(
    icon: ImageVector,
    label: String,
    isSelected: Boolean,
    onClick: () -> Unit
) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier
            .clip(RoundedCornerShape(8.dp))
            .clickable(onClick = onClick)
            .padding(vertical = 4.dp, horizontal = 12.dp), 
        verticalArrangement = Arrangement.Center
    ) {
        Icon(
            imageVector = icon,
            contentDescription = label,
            modifier = Modifier.size(24.dp),
            tint = if (isSelected) Color.White else Color.White.copy(alpha = 0.7f)
        )
        
        Text(
            text = label,
            fontSize = 11.sp,
            fontWeight = if (isSelected) FontWeight.Medium else FontWeight.Normal,
            color = if (isSelected) Color.White else Color.White.copy(alpha = 0.7f),
            textAlign = TextAlign.Center,
            maxLines = 1
        )
    }
}